/*
 * @Author: swl
 * @Date: 2023-07-03 11:04:56
 * @LastEditors: swl
 * @LastEditTime: 2023-07-08 14:23:17
 */
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { MusicplayService } from '../musicplay.service';

// 第三方数据库
import * as Parse from 'parse';
(Parse as any).serverURL = 'http://metapunk.cn:9999/parse';
Parse.initialize('dev');

@Component({
  selector: 'app-page-home',
  templateUrl: './page-home.component.html',
  styleUrls: ['./page-home.component.scss'],
})

// @ViewChild('myElement', { static: true }) myElement: ElementRef;
export class PageHomeComponent implements OnInit {
  constructor(public musicPlay: MusicplayService) {
    this.musicPlay.isPlaying = this.musicPlay.isPlaying;

    if (this.musicPlay.playingMusic) {
      this.SongList = this.musicPlay.playingMusic;
    }
    if (this.musicPlay.isPlaying) {
      // this.PlayMusic()
      // console.log(123);
      this.updateStatus();
    }
  }
content:any[]|undefined
  SongList: any;
  Sentence_text: String | undefined;
  Sentence_from: String | undefined;
  Sentence_author: String | undefined;
  Article_title: String | undefined;
  Article_author: String | undefined;
  // Article_content: String | undefined;
  Article_content: any;

  progress: number = 0; // 初始进度为0

  musicInfo: any;
  loveLogo: HTMLInputElement | undefined;
  isLoved: boolean = false;
  flag: boolean = false;
  isChange: boolean = this.musicPlay.isPlaying;
  async ngOnInit(): Promise<void> {
    this.getMusicInfo();
    this.getSentence();
    this.Article_content = this.getArticle();
    console.log(this.Article_content);
    this.loveLogo = this.loveLogo;
  }
  // 随机音乐接口
  async getMusicInfo() {
    console.log(this.musicPlay.isPlaying);
    if (this.musicPlay.isPlaying) return;
    let result = await fetch(
      'https://api.kit9.cn/api/netease_cloud_random_music/api.php', // 接口地址
      {
        method: 'GET',
      }
    );
    let data = await result.json();
    this.SongList = data.data;
    this.musicPlay.playingMusic = data.data;
    console.log(data);
  }

  // 实现当音乐处于播放或者暂停时，修改状态
  TogglePlay() {
    this.isChange = !this.isChange;
    if (this.musicPlay.isPlaying) {
      this.PauseMusic();
      this.musicPlay.isPlaying = false;
    } else {
      this.PlayMusic();
      this.musicPlay.isPlaying = true;
    }
  }
  // 音乐播放
  PlayMusic() {
    // const img = document.querySelector('.Song_img') as HTMLImageElement;
    // // 添加动画的旋转类
    // img.classList.add('animation2');
    // console.log(img);
    this.musicPlay.playMusic(this.SongList.music_address);
    // this.progress = this.musicPlay
    // this.musicPlay.progress$.subscribe((progress) => {
    //   this.progress = progress;
    //   if (this.progress == 100) {
    //     this.PauseMusic();
    //     this.isChange=false
    //   }
    // });
    // const img = document.querySelector('.Song_img') as HTMLImageElement;
    // console.log(img);
    // this.img_sign = img
    // console.log("-=-=-=-=-");
    // console.log(this.img_sign);
    // this.img_sign.classList.add("animation2")
    // 添加动画的旋转类
    // img.classList.add('animation2');
    this.updateStatus();
    this.addAnimation();
  }
  addAnimation() {
    this.musicPlay.isRotating = true;
  }
  deleteAnimation() {
    this.musicPlay.isRotating = false;
  }
  // 添加进度条
  updateStatus() {
    this.musicPlay.progress$.subscribe((progress) => {
      this.progress = progress;
      if (this.progress == 100) {
        this.PauseMusic();
        this.isChange = false;
      }
    });
  }

  // 音乐暂停
  PauseMusic() {
    this.musicPlay.pauseMusic();
    this.deleteAnimation();
  }

  isChecked: boolean = true;

  ToggleChecked() {
    this.isLoved = !this.isLoved;
    if (this.isChecked) {
      this.Love();
      this.isChecked = false;
      this.AddData();
    } else {
      this.UnLove();
      this.isChecked = true;
      this.DeleteData(this.SongList.music_address);
    }
  }

  // 收藏
  Love() {
    const love_logo = this.loveLogo;
    let love_count = document.querySelector('.love_count') as HTMLInputElement;
    if (love_logo) {
      love_logo.name = 'heart';
    }
    let count = parseInt(love_count.innerText);
    love_count.innerText = String(count + 1);
  }
  UnLove() {
    const love_logo = this.loveLogo;
    let love_count = document.querySelector('.love_count') as HTMLInputElement;
    if (love_logo) {
      love_logo.name = 'heart-outline';
    }
    let count = parseInt(love_count.innerText);
    love_count.innerText = String(count - 1);
  }

  // 将数据添加进数据库中
  async AddData() {
    console.log(this.SongList);
    this.flag = await this.QueryData();
    if (this.flag) {
      return;
    } else {
      // 将数据存入表中。
      let music = Parse.Object.extend('music_day');
      let musicList = new music();
      musicList.set(this.SongList);
      musicList.save();
    }
  }

  // 查询数据
  QueryData(): Promise<boolean> {
    return new Promise((resolve, reject) => {
      let query = new Parse.Query('music_day');
      query.equalTo('music_address', this.SongList.music_address);
      query.limit(10);
      query
        .find()
        .then((list) => {
          if (list.length > 0) {
            console.log(list);
            resolve(true);
          } else {
            resolve(false);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 删除数据库
  async DeleteData(url: string) {
    let query = new Parse.Query('music_day');
    query.equalTo('music_address', url);
    let music = await query.first();
    music?.destroy();
  }

  // 句子接口
  async getSentence() {
    console.log(this.musicPlay.isPlaying);
    // this.updateStatus()
    let result = await fetch(
      'https://v1.hitokoto.cn', // 接口地址
      {
        method: 'GET',
      }
    );
    let data = await result.json();
    console.log(data);
    this.Sentence_text = data.hitokoto;
    // console.log(this.Sentence_text?.substring(1,this.Sentence_text.length-1).split(","));
    this.Sentence_from = data.from;
    this.Sentence_author = data.creator;
  }

  // 文章接口
  async getArticle() {
    let result = await fetch(
      'https://interface.meiriyiwen.com/article/today?dev=1', // 接口地址
      {
        method: 'GET',
      }
    );
    let article = await result.json();
    // console.log(article.data);
    this.Article_title = article.data.title;
    this.Article_author = article.data.author;
    // console.log(article.data.content);
    this.Article_content = `${article.data.content}`;
    // this.Article_content = article.data;
    // console.log(this.Article_content.content);
    // return {
    //   article_title: article.data.title,
    //   article_author: article.data.author,
    //   article_content: article.data.content,
    // };
  }
}
